import { onBuildStatus } from './events';

export const initBuildStatus = (data: { window: Window }) => {
  const win = data.window;
  const doc = win.document;
  const iconElms = getFavIcons(doc);

  iconElms.forEach((iconElm) => {
    if (iconElm.href) {
      iconElm.dataset.href = iconElm.href;
      iconElm.dataset.type = iconElm.type;
    }
  });

  onBuildStatus(win, (buildStatus) => {
    updateBuildStatus(doc, buildStatus);
  });
};

const updateBuildStatus = (doc: Document, status: string) => {
  const iconElms = getFavIcons(doc);

  iconElms.forEach((iconElm) => {
    updateFavIcon(iconElm, status);
  });
};

export const updateFavIcon = (linkElm: HTMLLinkElement, status: string) => {
  if (status === 'pending') {
    linkElm.href = ICON_PENDING;
    linkElm.type = ICON_TYPE;
    linkElm.setAttribute('data-status', status);
  } else if (status === 'error') {
    linkElm.href = ICON_ERROR;
    linkElm.type = ICON_TYPE;
    linkElm.setAttribute('data-status', status);
  } else if (status === 'disabled') {
    linkElm.href = ICON_DISABLED;
    linkElm.type = ICON_TYPE;
    linkElm.setAttribute('data-status', status);
  } else {
    linkElm.removeAttribute('data-status');
    if (linkElm.dataset.href) {
      linkElm.href = linkElm.dataset.href;
      linkElm.type = linkElm.dataset.type;
    } else {
      linkElm.href = ICON_DEFAULT;
      linkElm.type = ICON_TYPE;
    }
  }
};

const getFavIcons = (doc: Document) => {
  const iconElms: HTMLLinkElement[] = [];
  const linkElms = doc.querySelectorAll('link');

  for (let i = 0; i < linkElms.length; i++) {
    if (
      linkElms[i].href &&
      linkElms[i].rel &&
      (linkElms[i].rel.indexOf('shortcut') > -1 || linkElms[i].rel.indexOf('icon') > -1)
    ) {
      iconElms.push(linkElms[i]);
    }
  }

  if (iconElms.length === 0) {
    const linkElm = doc.createElement('link');
    linkElm.rel = 'shortcut icon';
    doc.head.appendChild(linkElm);
    iconElms.push(linkElm);
  }

  return iconElms;
};

const ICON_DEFAULT =
  '';
const ICON_PENDING =
  '';
const ICON_ERROR =
  '';
const ICON_DISABLED =
  '';
const ICON_TYPE = 'image/x-icon';
